/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.emailbox.controller;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import com.google.common.collect.Lists;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.core.excel.EasyExcelUtils;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.annotation.ExportMode;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.emailbox.domain.EmailBox;
import com.jeeplus.emailbox.service.dto.EmailBoxDTO;
import com.jeeplus.emailbox.service.mapstruct.EmailBoxWrapper;
import com.jeeplus.emailbox.service.EmailBoxService;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 主席信箱Controller
 * @author 淋漓
 * @version 2024-08-05
 */

@Api(tags ="主席信箱")
@RestController
@RequestMapping(value = "/emailbox/emailBox")
public class EmailBoxController {

	@Autowired
	private EmailBoxService emailBoxService;

	@Autowired
	private EmailBoxWrapper emailBoxWrapper;

	@Autowired
	private UserService userService;

	/**
	 * 邮件列表数据
	 */
	@ApiLog("查询邮件列表数据")
	@ApiOperation(value = "查询邮件列表数据")
	@PreAuthorize("hasAuthority('emailbox:emailBox:list')")
	@GetMapping("list")
	public ResponseEntity<IPage<EmailBoxDTO>> list(EmailBoxDTO emailBoxDTO, Page<EmailBox> page) throws Exception {
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (emailBoxDTO, EmailBoxDTO.class);
		//查询发起人是我
		if(!emailBoxDTO.getOrganizerId().isEmpty())
		queryWrapper.eq("organizer_id",emailBoxDTO.getOrganizerId());
		//查询接收人是我
		if(!emailBoxDTO.getReceiverId().isEmpty()){
			queryWrapper.eq("receiver_id",emailBoxDTO.getReceiverId());
		}
		//查询待浏览的邮件
		if(!emailBoxDTO.getScan().isEmpty()){
			queryWrapper.like("status","未处理");
			queryWrapper.eq("receiver_id",emailBoxDTO.getReceiverId());
		}
		IPage<EmailBoxDTO> result = emailBoxWrapper.toDTO ( emailBoxService.page (page, queryWrapper) );
		return ResponseEntity.ok (result);
	}


	/**
	 * 根据Id获取邮件数据
	 */
	@ApiLog("根据Id获取邮件数据")
	@ApiOperation(value = "根据Id获取邮件数据")
	@PreAuthorize("hasAnyAuthority('emailbox:emailBox:view','emailbox:emailBox:add','emailbox:emailBox:edit')")
	@GetMapping("queryById")
	public ResponseEntity<EmailBoxDTO> queryById(String id) {
		return ResponseEntity.ok ( emailBoxWrapper.toDTO ( emailBoxService.getById ( id ) ) );
	}

	/**
	 * 保存邮件
	 */
	@ApiLog("保存邮件")
	@ApiOperation(value = "保存邮件")
	@PreAuthorize("hasAnyAuthority('emailbox:emailBox:add','emailbox:emailBox:edit')")
	@PostMapping("save")
	public  ResponseEntity <String> save(@Valid @RequestBody EmailBoxDTO emailBoxDTO) {
		if (emailBoxDTO.getStatus()== null||emailBoxDTO.getStatus().isEmpty()){
			emailBoxDTO.setStatus("未处理");
			emailBoxDTO.setScan("no");
			emailBoxDTO.setReflectDate(new Date());
			User user = userService.getById(emailBoxDTO.getReceiverId());
			if(user.getName()!=null) {
				emailBoxDTO.setReceiverName(user.getName());
			}
			//新增或编辑表单保存
			emailBoxService.saveOrUpdate (emailBoxWrapper.toEntity (emailBoxDTO));
			return ResponseEntity.ok ( "发送邮件成功" );
		}
		else {
			emailBoxDTO.setStatus("已反馈");
			emailBoxDTO.setFeebackDate(new Date());
			emailBoxService.saveOrUpdate (emailBoxWrapper.toEntity (emailBoxDTO));
			emailBoxDTO.setId(null);
			String orgId=emailBoxDTO.getOrganizerId();
			emailBoxDTO.setOrganizerId(emailBoxDTO.getReceiverId());
			emailBoxDTO.setReceiverId(orgId);
			String orgName=emailBoxDTO.getOrganizerName();
			emailBoxDTO.setOrganizerName(emailBoxDTO.getReceiverName());
			emailBoxDTO.setReceiverName(orgName);
			//新增或编辑表单保存
			emailBoxService.saveOrUpdate (emailBoxWrapper.toEntity (emailBoxDTO));
			return ResponseEntity.ok ( "保存邮件成功" );
		}

	}


	/**
	 * 标记全部阅读
	 */
	@ApiLog("标记全部阅读")
	@ApiOperation(value = "标记全部阅读")
	@PreAuthorize("hasAuthority('emailbox:emailBox:view')")
	@PostMapping("IsScan")
	public ResponseEntity <String> IsScan(@RequestBody String ids) {
		if (ids.isEmpty()||ids==null){
			return ResponseEntity.ok ( "没有新邮件查看" );
		}
		String idArray[] = ids.split(",");
		for (int i=0;i<idArray.length;i++) {
			EmailBoxDTO emailBoxDTO = new EmailBoxDTO();
			emailBoxDTO.setId(idArray[i]);
			emailBoxDTO.setScan("yes");
			emailBoxService.updateById (emailBoxWrapper.toEntity (emailBoxDTO));
		}
		return ResponseEntity.ok( "已阅读" );
	}

	/**
	 * 删除邮件
	 */
	@ApiLog("删除邮件")
	@ApiOperation(value = "删除邮件")
	@PreAuthorize("hasAuthority('emailbox:emailBox:del')")
	@DeleteMapping("delete")
	public ResponseEntity <String> delete(String ids) {
		String idArray[] = ids.split(",");
        emailBoxService.removeByIds ( Lists.newArrayList ( idArray ) );
		return ResponseEntity.ok( "删除邮件成功" );
	}

    /**
     * 导出邮件数据
     *
     * @param emailBoxDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出邮件数据")
    @PreAuthorize("hasAnyAuthority('emailbox:emailBox:export')")
    @GetMapping("export")
    public void exportFile(EmailBoxDTO emailBoxDTO, Page <EmailBox> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename ( );
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (emailBoxDTO, EmailBoxDTO.class);
        if ( ExportMode.current.equals ( options.getMode ( ) ) ) { // 导出当前页数据

        } else if ( ExportMode.selected.equals ( options.getMode ( ) ) ) { // 导出选中数据
            queryWrapper.in ( "id", options.getSelectIds () );
        } else { // 导出全部数据
            page.setSize ( -1 );
            page.setCurrent ( 0 );
        }
        List < EmailBox> result = emailBoxService.page ( page, queryWrapper ).getRecords ( );
        EasyExcelUtils.newInstance ( emailBoxService, emailBoxWrapper ).exportExcel ( result,  options.getSheetName ( ), EmailBoxDTO.class, fileName,options.getExportFields (), response );
    }

    /**
     * 导入邮件数据
     *
     * @return
     */
    @PreAuthorize("hasAnyAuthority('emailbox:emailBox:import')")
    @PostMapping("import")
    public ResponseEntity importFile(MultipartFile file) throws IOException {
        String result = EasyExcelUtils.newInstance ( emailBoxService, emailBoxWrapper ).importExcel ( file, EmailBoxDTO.class );
        return ResponseEntity.ok ( result );
    }

    /**
     * 下载导入邮件数据模板
     *
     * @param response
     * @return
     */
    @PreAuthorize ("hasAnyAuthority('emailbox:emailBox:import')")
    @GetMapping("import/template")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        String fileName = "邮件数据导入模板.xlsx";
        List<EmailBoxDTO> list = Lists.newArrayList();
        EasyExcelUtils.newInstance ( emailBoxService, emailBoxWrapper ).exportExcel ( list,  "邮件数据", EmailBoxDTO.class, fileName, null, response );
    }


}
